package chat.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import chat.server.user.UserManagementMap;

public class Chat implements Runnable {
	private Socket socket = null;
	private BufferedReader in = null;
	private boolean close = false;
	private String fromUser = null;
	private String toUser = null;
	
	/**
	 * Chat dedicated to single client that connects to the server socket.
	 * 
	 * @param socket
	 */
	public Chat(Socket socket) {
		this.socket = socket;
		try {
			//have the output stream and input stream of the socket
			//
			//
//			out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
			in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		try {
			System.out.println("Inside Chat");
			String str = null;
			
			//get the from user and maintain user socket table.
			//
			fromUser = in.readLine();
			System.out.println("got current user = " + fromUser);
			UserManagementMap.addUser(fromUser, socket);
			
			toUser = in.readLine();
			System.out.println("got to user = " + toUser);
			//wait until to user socket is available in the map.
			while(UserManagementMap.getSocket(toUser) == null){
				System.out.println("waiting until "+toUser+" connected");
			}
			// writer to write the incoming message to the socket.
			PrintWriter toWriter = new PrintWriter(UserManagementMap.getSocket(toUser).getOutputStream());			
			while ((str = in.readLine()) != null) {
				System.out.println(str);
				toWriter.write(str);
				toWriter.write("\n");
				toWriter.flush();
				if (str.equals("bye")) {
					System.out.println("Logging out.");
					break;
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				in.close();
//				out.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
